package vule.coordinates;

import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;

import vule.random.Rnd;

public class CoordinatesManager {

	
	public List<Rectangle> addedComponents = new ArrayList<Rectangle>();
	
	private int maxX = 0;
	private int maxY = 0;
	
	public CoordinatesManager(JComponent component) {
		maxX = component.getSize().width;
		maxY = component.getSize().height;
	}
	
	private int getRandomX(int componentWidth) {
		return Rnd.next(maxX - componentWidth);
	}

	private int getRandomY(int componentHeight) {
		return Rnd.next(maxY - componentHeight);
	}
	
	
	public Rectangle getRandomPosition(int componentWidth, int componentHeight) {
		int x = getRandomX(componentWidth);
		int y = getRandomY(componentHeight);
		return new Rectangle(x, y, componentWidth, componentHeight);
	}
	
	public void addComponent(Rectangle component) {
		addedComponents.add(component);
	}
	
	public void clearComponents() {
		addedComponents.clear();
	}
	
	public Rectangle getRandomFreePosition(int componentWidth, int componentHeight) {
		while (true) {
			Rectangle rnd = getRandomPosition(componentWidth, componentHeight);
			if (!intersects(rnd)) {
				addedComponents.add(rnd);
				return rnd;
			}
		}
	}

	private boolean intersects(Rectangle rnd) {
		for (Rectangle rectangle : addedComponents) {
			if (rectangle.intersects(rnd)) {
				return true;
			}
		}
		return false;
	}
}
